package com.fsts.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JTextArea;

/**
 * 文件发送类
 * 
 * 
 * @version 1.0
 * @since JDK1.6(建议)
 */
public class SendFile {
	public void sendFile(String destIp, int port, String filePath,
			JTextArea infoTextArea) {
		DataOutputStream out = null;
		DataInputStream in = null;
		Socket socket = null;
		try {
			infoTextArea.append("请求对主机址......\n");
			socket = new Socket(destIp, port);
			infoTextArea.append("连接对方主机成功>>>>>\n");
			out = new DataOutputStream(socket.getOutputStream());
			in = new DataInputStream(socket.getInputStream());
			infoTextArea.append("向对方发送信息......\n");
			infoTextArea.append("向对方发送信息成功>>>>>\n");
			infoTextArea.append("接受对方返回信息>>>>\n");
			File file = new File(filePath);
			infoTextArea.append("文件总长度：" + file.length() + " \n");
			byte[] b = new byte[1000000];
			FileInputStream fileInputStream = new FileInputStream(file);
			out.writeUTF(file.getName());
			out.writeLong(file.length());
			while (true) {
				// 返回读入的字节长度，其实就是b数组的长度
				int read = fileInputStream.read(b);
				// 都完以后返回-1
				if (read == -1) {
					break;
				}
				// 将指定字节数组中从偏移量 0 开始的 read 个字节写入基础输出流。
				out.write(b, 0, read);
			}
			infoTextArea.append("发送完成>>>>>\n");
			out.flush();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			infoTextArea.append("接收方连接错误...\n");
		} catch (IOException e) {
			e.printStackTrace();
			infoTextArea.append("读取文件错误...\n");
		} finally {
			try {
				out.close();
				in.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
}
